package com.bupt.ilink.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bupt.ilink.entity.Studyspace.*;
import com.bupt.ilink.mapper.CourseSourceMapper;
import com.bupt.ilink.mapper.StudyFileSourceMapper;
import com.bupt.ilink.mapper.StudyTeacherCourseMapper;
import com.bupt.ilink.mapper.StudyWebSourseMapper;
import com.bupt.ilink.service.FileTranscriptionService;
import com.bupt.ilink.service.OssService;
import com.bupt.ilink.service.StudyaboutStudentService;
import com.bupt.ilink.service.StudyaboutTeacherService;
import com.bupt.ilink.utils.R;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Service
public class StudyaboutStudentServiceImpl extends ServiceImpl<StudyTeacherCourseMapper, StudyTeacherCourse> implements StudyaboutStudentService {

    private static final Logger logger = LoggerFactory.getLogger(StudyaboutStudentServiceImpl.class);

    @Autowired
    private StudyFileSourceMapper studyFileSourceMapper;
    @Autowired
    private CourseSourceMapper courseSourceMapper;
    @Autowired
    private StudyWebSourseMapper studyWebSourseMapper;

    @Autowired
    private OssService ossService;
    @Autowired
    private FileTranscriptionService fileTranscriptionService;


    @Transactional
    @Override
    public R moveDocumentResource(Long resourceId, StudyCourseFile newFolder, Long courseId) {
        // 获取文档资源
        StudyFileSource fileSource = studyFileSourceMapper.selectById(resourceId);
        if (fileSource == null) {
            logger.error("无效文档资源ID");
            return R.failure("无效文档资源ID");
        }

        // 更改文档资源的路径
        String originalFilePath = fileSource.getFilesourcePath();
        String objectName = originalFilePath.substring(originalFilePath.lastIndexOf("/") + 1);
        originalFilePath = originalFilePath.substring(0, originalFilePath.lastIndexOf("/") + 1);
        String newFilePath = newFolder.getFilePath();

        // 执行OSS移动操作，失败时直接返回
        boolean ossMove;
        try {
            ossMove = ossService.moveFile(objectName, originalFilePath, newFilePath);
        } catch (Exception e) {
            logger.error("OSS 文档文件移动失败", e);
            return R.failure("OSS 文档文件移动失败", e);
        }

        if (!ossMove) {
            logger.error("OSS 文档文件移动失败");
            return R.failure("OSS 文档文件移动失败");
        }

        // 在OSS操作成功后，执行MySQL事务
        try {
            // 更改文档资源的目录ID
            fileSource.setFileId(newFolder.getCourseFileId());
            // 更新数据库中的文件路径
            fileSource.setFilesourcePath(newFilePath+objectName);
            studyFileSourceMapper.updateById(fileSource);
        } catch (Exception e) {
            // 如果数据库操作失败，可以考虑回滚OSS操作
            logger.error("文档数据库更新失败", e);
            ossService.moveFile(objectName, newFilePath, originalFilePath);
            return R.failure("文档数据库更新失败", e);
        }
        logger.info("文件资源移动成功");
        return R.ok("文件资源移动成功");
    }

    @Transactional
    @Override
    public R moveAudioVideoResource(Long resourceId, StudyCourseFile newFolder, Long courseId) {
        // 获取音视频资源
        CourseSource courseSource = courseSourceMapper.selectById(resourceId);
        if (courseSource == null) {
            logger.error("无效音视频资源ID");
            return R.failure("无效音视频资源ID");
        }

        // 更改音视频资源的路径
        String originalFilePath = courseSource.getFilesourcePath();
        String objectName = originalFilePath.substring(originalFilePath.lastIndexOf("/") + 1);
        originalFilePath = originalFilePath.substring(0, originalFilePath.lastIndexOf("/") + 1);
        String newFilePath = newFolder.getFilePath();

        boolean ossMove;
        boolean tranMove;
        long sourceId = courseSource.getCourseSourceId();
        try {
            // 先移动文件
            ossMove = ossService.moveFile(objectName, originalFilePath, newFilePath);
            if (!originalFilePath.endsWith("/")) {
                originalFilePath += "/";
            }
            if (!newFilePath.endsWith("/")) {
                newFilePath += "/";
            }
            logger.info("OSS麻紫嫣转写原路径{}，目标路径{}",originalFilePath + sourceId + "/", newFilePath + sourceId + "/");
            tranMove = ossService.moveDirectory(originalFilePath + sourceId + "/", newFilePath + sourceId + "/");
        } catch (Exception e) {
            logger.error("OSS 音视频文件移动失败", e);
            return R.failure("OSS 音视频文件移动失败", e);
        }

        if (!ossMove && !tranMove) {
            logger.error("OSS 音视频文件移动失败");
            return R.failure("OSS 音视频文件移动失败");
        }

        // 在OSS操作成功后，执行MySQL事务
        try {
            // 更改音视频资源的目录ID
            courseSource.setFileId(newFolder.getCourseFileId());

            // 更新数据库中的文件路径
            courseSource.setFilesourcePath(newFilePath+objectName);
            courseSource.setUpdatedAt(new Date());
            courseSourceMapper.updateById(courseSource);

            // 更新转写信息
            boolean tranMoveMysql = fileTranscriptionService.modifyFileTransInfoPath(courseSource.getTaskId(), newFolder.getFilePath());
            if (!tranMoveMysql) {
                throw new RuntimeException("转写 音视频文件移动失败");
            }
        } catch (Exception e) {
            // 如果数据库操作失败，可以考虑回滚OSS操作
            ossService.moveFile(objectName, newFilePath, originalFilePath);
            ossService.moveFile("", newFilePath + sourceId + "/", originalFilePath + sourceId + "/");
            logger.error("音视频数据库更新失败", e);
            return R.failure("音视频数据库更新失败", e);
        }
        logger.info("音视频资源移动成功");
        return R.ok("音视频资源移动成功");
    }


    @Transactional
    @Override
    public R moveWebResource(Long resourceId, StudyCourseFile newFolder, Long courseId) {
        // 获取网页资源
        StudyWebSourse webSource = studyWebSourseMapper.selectById(resourceId);
        if (webSource == null) {
            return R.failure("无效网页资源ID");
        }

        // 在OSS操作成功后，执行MySQL事务
        try {
            // 更改网页资源的目录ID
            webSource.setFileId(newFolder.getCourseFileId());

            // 更新上传时间
            webSource.setUploadedAt(new Date());
            studyWebSourseMapper.updateById(webSource);
        } catch (Exception e) {
            return R.failure("网页数据库更新失败", e);
        }

        return R.ok("网页资源移动成功");
    }

}
